package tau.dimes.visualization.applet.aviRecord;

import java.io.ByteArrayInputStream;
import java.io.IOException;

import javax.jnlp.FileContents;
import javax.jnlp.FileSaveService;
import javax.jnlp.ServiceManager;
import javax.jnlp.UnavailableServiceException;

import processing.core.PApplet;

/**
 * Implements AVI move recording.
 */
public class AVIRecorder
{
	private final PApplet applet;
	private final MJPEGGenerator mJpegGenerator;

	/**
	 * Constructs a new AVIRecorder.
	 * @param applet A reference to the containing applet.
	 * @param framerate Movie frame rate.
	 * @param numFrames Total number of frames.
	 * @throws IOException
	 * @throws UnavailableServiceException
	 */
	public AVIRecorder(PApplet applet, double framerate, int numFrames) throws IOException,
		UnavailableServiceException
	{
		this.applet = applet;

		FileSaveService fss = (FileSaveService) ServiceManager.lookup("javax.jnlp.FileSaveService");
		ByteArrayInputStream bais = new ByteArrayInputStream(new byte[0]);
		FileContents fileContents = fss
			.saveFileDialog(null, new String[] { "avi" }, bais, "export.avi");

		if (fileContents == null)
			throw new IOException("No file selected");
		
		this.mJpegGenerator = new MJPEGGenerator(fileContents, applet.width, applet.height,
			framerate, numFrames);
	}

	/**
	 * Adds the current frame to the movie.
	 * @throws IOException
	 */
	public void recordImage() throws IOException
	{
		mJpegGenerator.addImage(applet.g.image);
	}

	/**
	 * Finished the movie.
	 * @throws IOException
	 */
	public void finish() throws IOException
	{
		mJpegGenerator.finishAVI();
	}
}
